<?php
/**
 * 高德地图api
 * @wfs: 2020/10/16
 */
namespace base\map;
use help\HttpHelp;
use lib\wechat\Map;
use base\service\HttpService;

// use base\map\AmapApi;
// 根据经纬度获取位置		AmapApi::getAddress($latitude,$longitude);		
// 获取经纬度间的距离		AmapApi::getDistance(string $origins, string $destination);		
// 获取最优路径					AmapApi::getOptimalRoute();		

class AmapApi {
	//key 
	protected static $key = '5f2ec11132ca118230d8846d28e48efc';
	//api
	protected static $api = [
        'distance' => 'https://restapi.amap.com/v3/distance',
        'parameters' => 'https://restapi.amap.com/v3/geocode/regeo?parameters',
    ];
	
	/**
	* 根据经纬度获取位置
	* @param  $latitude 
	* @param  $longitude 
	* @return  
	*/
	public static function getAddress($latitude,$longitude){
		$param['location'] = $longitude.','.$latitude; 
		$param['key'] =  self::$key; 
		$res = HttpHelp::getRequest(self::$api['parameters'],$param);
		$res = json_decode($res,true);
		if($res['info'] == 'OK'){
			return $res['regeocode'];
		}else{
			return false;
		}
	}
	
	/**
	* 获取经纬度间的距离
	* @param  $origins  string '114.465302,40.004717|114.465302,40.004717'
	* @param  $destination string '114.465302,40.004717'
	* @return  
	*/
	public static function getDistance(string $origins, string $destination){
		$param['origins'] = $origins; 
		$param['destination'] = $destination; 
		$param['key'] =  self::$key; 
		$param['type'] = "1"; 
		return HttpHelp::getRequest(self::$api['distance'],$param);
	}
	
	/**
	* 获取最优路径
	* @param  $origins  string '114.465302,40.004717'
	* @param  $waypoints string '114.465302,40.004717|114.465302,40.004717'
	* @return  
	*/
	public static function getOptimalRoute(string $waypoints, string $origins,array $arr=[]){
		$coordinate = explode("|",$waypoints);
		if(count($arr) == 0 && count($coordinate) < 2){
			$arr[] = $origins;
			$arr[] = $coordinate[0];
			return $arr;
		}
		if(count($arr) == 0){
			$arr[] = $origins;
		}
		$res = json_decode( self::getDistance($waypoints,$origins) , true);
		$results = $res['results'];
		$distance = self::searchmin($results,'distance');
		$origin = $coordinate[$distance['key']];
		unset($coordinate[$distance['key']]);
		$arr[] = $origin;
		if(count($coordinate) > 1){
			return self::getOptimalRoute(join("|",$coordinate),$origin,$arr);
		}else{
			$arr[] = $coordinate[0];
			return $arr;
		}
		
	}
	
	// 最小值
	private function searchmin($arr,$field) {
	    if(!is_array($arr) || !$field){ //判断是否是数组以及传过来的字段是否是空
	        return false;
	    }
		$mix = $arr[0][$field];
		$key = 0;
		foreach($arr as $k => $val){
			if($mix > $val[$field]){
				$mix = $val[$field];
				$key = $k;
			}
		}
	    return ["mix"=>$mix,'key'=>$key];  
	}
	
	
	
	
}